package com.scoring.system.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.scoring.system.annotation.SkipSecurityCheck;
import com.scoring.system.pojo.Achievement;
import com.scoring.system.pojo.Classes;
import com.scoring.system.pojo.ComprehensiveQuality;
import com.scoring.system.pojo.ExpandQuality;
import com.scoring.system.pojo.MoralAchievement;
import com.scoring.system.pojo.RewardPunishment;
import com.scoring.system.pojo.Student;
import com.scoring.system.pojo.Term;
import com.scoring.system.pojo.User;
import com.scoring.system.service.AchievementService;
import com.scoring.system.service.ClassCurriculumService;
import com.scoring.system.service.ClassesService;
import com.scoring.system.service.ComprehensiveQualityService;
import com.scoring.system.service.ExpandQualityService;
import com.scoring.system.service.MoralAchievementService;
import com.scoring.system.service.RewardPunishmentService;
import com.scoring.system.service.StudentService;
import com.scoring.system.service.TermSerivce;
import com.scoring.system.service.UserService;
@Controller
@RequestMapping("/instructor")
public class InstructorController {
	private static Logger logger = Logger.getLogger(AdminController.class);
	private Map<String, Object> map;
	
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ClassesService classesService;
	
	@Autowired
	private StudentService studentService;
    
	@Autowired
	private TermSerivce termSerivce;
	
	@Autowired
	private AchievementService achievementService;
	
	@Autowired
	private ComprehensiveQualityService qualityService;
	
	@Autowired
	private RewardPunishmentService rpService;
	
	@Autowired
	private MoralAchievementService maService;
	
	@Autowired
	private ExpandQualityService eqSerive;
	
	@Autowired
	private ClassCurriculumService ccService;
	
	@RequestMapping("getInstructor")
	@SkipSecurityCheck
	@ResponseBody
	public Map getInstructor(HttpServletRequest request, ModelMap modelMap) {
		HttpSession se = request.getSession();
		User instructor = (User) se.getAttribute("user");
		logger.info("get instructor[" + instructor + "]");
		map = new HashMap();
		map.put("instructor", instructor);
		return map;
	}

	@RequestMapping("updateInstructorMessage")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateInstructorMessage(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		User instructor = (User) se.getAttribute("user");
		String userId = request.getParameter("user_id");
		String mailbox = request.getParameter("mailbox");
		String phone = request.getParameter("phone");
		logger.info("get InstructorMessage[" + "userId=" + userId + ",mailbox=" + mailbox + ",phone=" + phone + "]");
		if (!userId.equals(instructor.getUserNumber())) {
			map.put("isSame", "no");
		} else {
			instructor.setMailbox(mailbox);
			instructor.setPhone(phone);
			int count = userService.updateUser(instructor);
			if (count > 0) {
				map.put("update", "success");
			} else {
				map.put("update", "failed");
			}
		}
		return map;
	}

	@RequestMapping("updateInstructorPassword")
	@SkipSecurityCheck
	@ResponseBody
	public Map updatePssword(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String oldPassword = request.getParameter("old_password");
		String newPassword = request.getParameter("new_password");
		String confrimPassword = request.getParameter("confirm_password");
		logger.info("get AdminPassword:old_password" + oldPassword + ",new_password=" + newPassword
				+ ",confirm_password=" + confrimPassword);
		HttpSession se = request.getSession();
		User instructor = (User) se.getAttribute("user");
		if (!oldPassword.equals(instructor.getPassword())) {
			map.put("isExsit", "false");
		} else if (!newPassword.equals(confrimPassword)) {
			map.put("equal", "false");
		} else {
			instructor.setPassword(newPassword);
			int count = userService.updateUser(instructor);
			if (count > 0) {
				map.put("update", "success");
			} else {
				map.put("update", "false");
			}
		}
		return map;
	}
	
	@RequestMapping("listClassByInstructor")
	@SkipSecurityCheck
	@ResponseBody
	public Map listClassByInstructor(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		HttpSession se =request.getSession();
		User instructor =(User)se.getAttribute("user");
		logger.info("get user="+instructor);
		List<Classes> clazz =new ArrayList<>();
		List<Classes> clazzs =classesService.listClassByUserId(instructor.getId());
		for(Classes cla : clazzs ){
			logger.info("get class:"+cla);
			if(cla.getIsDeleted()!=true){
				clazz.add(cla);
			}
		}
		map.put("classes", clazz);
		return map;
	}
	@RequestMapping("listStudentByClass")
	@SkipSecurityCheck
	@ResponseBody
	public Map listStudentByClass(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		HttpSession se =request.getSession();
		String clazz= request.getParameter("class_name");
		Classes cla=classesService.getClassByName(clazz);
		se.setAttribute("classId", cla.getId());
		List<Student> student =new ArrayList<>();
		List<Student> students =studentService.listStudentByClassId(cla.getId());
		for(Student stu : students ){
			logger.info("get student:"+stu);
			if(stu.getIsDeleted()!=true){
				student.add(stu);
			}
		}
		map.put("student", student);
		return map;
	}
	@RequestMapping("getStudent")
	@SkipSecurityCheck
	@ResponseBody
	public Map getStudent(HttpServletRequest request, ModelMap modelMap) {
		HttpSession se = request.getSession();
		map = new HashMap();
		String studentId = request.getParameter("student_id");
		logger.info("get studentId=" + studentId);
		Student student=studentService.getStudentByStudentNumber(studentId);
		logger.info("get student:" +student.getName());
		se.setAttribute("student", student);
		map.put("student", student);
		return map;

	}
	@RequestMapping("getStudentId")
	@SkipSecurityCheck
	@ResponseBody
	public Map getStudentId(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String studentName = request.getParameter("student_name");
		logger.info("get studentName=" + studentName);
		Student student=studentService.getStudentByName(studentName);
		logger.info("get student:" +student.getName());
		map.put("studentId", student.getStudentNumber());
		return map;
		
	}
	@RequestMapping("updateStudent")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateStudent(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		HttpSession se = request.getSession();
		String stduentName = request.getParameter("student_name");
		String phone = request.getParameter("phone");
		String mailbox =request.getParameter("mailbox");
		Student student =(Student)se.getAttribute("student");
		logger.info("get stduentName ="+ stduentName +" ,phone=" +phone+",mailbox="+mailbox);
		student.setMailbox(mailbox);
		student.setName(stduentName);
        student.setPhone(phone);
	    int count = studentService.updateStudent(student);
		if(count>0){
			map.put("update", "true");
		}else{
			map.put("update", "false");
		}
		return map;
	}
	@RequestMapping("listTermByClass")
	@SkipSecurityCheck
	@ResponseBody
	public Map listTermByClass(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		String clazz = request.getParameter("class_name");
		logger.info("get class="+clazz);
		int index= clazz.indexOf("2");
		int year =Integer.valueOf(clazz.substring(index,index+4));
		logger.info("get year="+year);
		List<Term> term =new ArrayList<>();
		List<Term> terms =termSerivce.listTerm();
		for(Term te : terms ){
			logger.info("get term:"+te);
			int year1=Integer.valueOf(te.getName().substring(0, 4));
			logger.info("get year1="+year1);
			if(year-year1==0||year-year1>=-3){
				term.add(te);
			}
		}
		map.put("term", term);
		return map;
	}
	@RequestMapping("listAchievementByClassAndTerm")
	@SkipSecurityCheck
	@ResponseBody
	public Map listAchievementByClassAndTerm(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String clazz = request.getParameter("class_name");
		String term = request.getParameter("term");
		Classes cla = classesService.getClassByName(clazz);
		List<Achievement> achievement = new ArrayList<>();
		List<Achievement> achievements =new ArrayList<>();
		if("所有学期".equals(clazz)){
			achievements= achievementService.listAchievementByClassId(cla.getId());
			for (Achievement ach : achievements) {
				logger.info("get achievement:" + ach);
				if (ach.getIsDeleted() != true) {
					achievement.add(ach);
			}
		 }
		}else{
			achievements = achievementService.listAchievementByClassIdAndTerm(cla.getId(), term);
			for (Achievement ach : achievements) {
				logger.info("get achievement:" + ach);
				if (ach.getIsDeleted() != true) {
					achievement.add(ach);
				}
			}
		}
		map.put("achievement", achievement);
		return map;
	}
	@RequestMapping("listRewardPunishmentByStudent")
	@SkipSecurityCheck
	@ResponseBody
	public Map listRewardPunishmentByStudent(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		HttpSession se =request.getSession();
		String studentName= request.getParameter("student_name");
		Student student =studentService.getStudentByName(studentName);
		se.setAttribute("studentId", student.getId());
		List<RewardPunishment> rewardPunishment =new ArrayList<>();
		List<RewardPunishment> rewardPunishments =rpService.listRewardPunishmentByStudentID(student.getId());
		if(rewardPunishments.size()==0){
			map.put("isNull", "yes");
		}else{
			for(RewardPunishment rp : rewardPunishments ){
				logger.info("get rewardPunishment:"+rp);
				if(rp.getIsDeleted()!=true){
					rewardPunishment.add(rp);
				}
			}
			map.put("rewardPunishment", rewardPunishment);
		}
		return map;
	}
	@RequestMapping("createRewardPunishment")
	@SkipSecurityCheck
	@ResponseBody
	public Map createRewardPunishment(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		HttpSession se = request.getSession();
		String content=request.getParameter("content");
		String score=request.getParameter("score");
		int studentId = (int)(se.getAttribute("studentId"));
		User instructor =(User)se.getAttribute("user");
		logger.info("get content ="+ content +" ,score=" +score);
		RewardPunishment rewardPunishment =new RewardPunishment();
		rewardPunishment.setStudentId(studentId);
		rewardPunishment.setContent(content);
		rewardPunishment.setScore(score);
		rewardPunishment.setUserId(instructor.getId());
		rewardPunishment.setIsDeleted(false);
		int count =rpService.saveRewardPunishment(rewardPunishment);
		if(count>0){
			map.put("success", "true");
		}else{
			map.put("success", "false");
		}
		return map;
	}
	@RequestMapping("getRewardPunishment")
	@SkipSecurityCheck
	@ResponseBody
	public Map getRewardPunishment(HttpServletRequest request, ModelMap modelMap) {
		HttpSession se = request.getSession();
		map = new HashMap();
		int id = Integer.valueOf(request.getParameter("id"));
		logger.info("get rewardPunishmentId=" + id);
		RewardPunishment rewardPunishment =rpService.getRewardPunishmentById(id);
		logger.info("get rewardPunishment:" +rewardPunishment);
		se.setAttribute("rewardPunishment", rewardPunishment);
		map.put("rewardPunishment", rewardPunishment);
		return map;

	}
	@RequestMapping("deleteRewardPunishment")
	@SkipSecurityCheck
	@ResponseBody
	public Map deleteRewardPunishment(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		int id = Integer.valueOf(request.getParameter("id"));
		logger.info("get rewardPunishmentid=" + id);
		int count = rpService.softDelete(id);
		if (count > 0) {
			map.put("isDelete", "true");
		} else {
			map.put("isDelete", "failed");
		}
		return map;

	}
	@RequestMapping("updateRewardPunishment")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateRewardPunishment(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		HttpSession se = request.getSession();
		String content = request.getParameter("content");
		String score = request.getParameter("score");
		logger.info("get content ="+ content +" ,phone=" +score);
		RewardPunishment rewardPunishment =(RewardPunishment)se.getAttribute("rewardPunishment");
		rewardPunishment.setContent(content);
		rewardPunishment.setScore(score);
	    int count = rpService.updateRewardPunishment(rewardPunishment);
		if(count>0){
			map.put("update", "true");
		}else{
			map.put("update", "false");
		}
		return map;
	}
	@RequestMapping("listComprehensiveQualityByClass")
	@SkipSecurityCheck
	@ResponseBody
	public Map listComprehensiveQualityByClass(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		String className= request.getParameter("class_name");
		Classes clazz=classesService.getClassByName(className);
		logger.info("get class="+className);
		boolean init=true;
		Calendar cal = Calendar.getInstance();
		int year =cal.get(Calendar.YEAR);
        int index = className.indexOf("2");
        int year1=Integer.valueOf(className.substring(index, index+4));
        List<ComprehensiveQuality> comprehensiveQuality =new ArrayList<>();
        if(year-year1>=4){
        	map.put("graduate", "yes");
        	while(init){
        		List<ComprehensiveQuality> comprehensiveQualitys =qualityService.listComprehensiveQualityByClassId(clazz.getId());
        		if(comprehensiveQualitys.size()==0){
        			addMessageToQulity(clazz);
        			init =true;
        		}else{
        			for(ComprehensiveQuality cq : comprehensiveQualitys ){
        				logger.info("get rewardPunishment:"+cq);
        				if(cq.getIsDeleted()!=true){
        					comprehensiveQuality.add(cq);
        				}
        			}
        			init = false;
        		}
        	}
        }else{
        	map.put("graduate", "no");
        }
		map.put("comprehensiveQuality", comprehensiveQuality);
		return map;
	}
	
	public void addMessageToQulity(Classes clazz){
		logger.info(clazz);
		List<Student> students =studentService.listStudentByClassId(clazz.getId());
		ComprehensiveQuality comprehensiveQuality =new ComprehensiveQuality();
		String wScore="";
		String eScore="";
		double total=0;
		double total1=0;
		int count=0;
		int count1=0;
		int add=0;
		int reduce=0;
		for(Student student:students){
			logger.info("get student="+student.getName());
			List<Achievement> achievement=achievementService.listAchievementByStudentId(student.getId());
			MoralAchievement moralAchievement=maService.getMoralAcievementByStudent(student.getId());
			ExpandQuality expandQuality =eqSerive.getExpandQualityByStduent(student.getId());
			for(Achievement ac:achievement){
				logger.info("get achievement="+ac);
				String type =ccService.getClassCurriculumByCourse(ac.getCourseId()).getCurriculumNature();
				logger.info("get type ="+type);
				if(ac.getIsDeleted()!=true&&"必修课".equals(type)){
						count ++;
						total =total+Integer.valueOf(ac.getScore());
				}else if(ac.getIsDeleted()!=true&&"选修课".equals(type)){
					   count1++;
					   total1 =total1+Integer.valueOf(ac.getScore());
				}
			}
			logger.info("get count="+count+",total="+total+",count1="+count1+",total1="+total1);
			wScore=String.valueOf((int)((total/count)*0.8+(total1/count1)*0.2));
			logger.info("get vScore="+moralAchievement.getTotalScore()+",wScore="+wScore+",eqScore="+expandQuality.getTotalScore());
			total=0;
			total1=0;
			count=0;
			count1=0;
			List<RewardPunishment> rp =rpService.listRewardPunishmentByStudentID(student.getId());
			if(rp.size()>0){
				for(RewardPunishment rpt:rp){
					if("+".equals((rpt.getScore()).substring(0, 1))){
						add=add+Integer.valueOf(rpt.getScore().substring(1));
					}else{
						reduce=reduce+Integer.valueOf(rpt.getScore().substring(1));
					}
					logger.info("get add="+add+",reduce="+reduce);
				}
				if(add-reduce>0){
					eScore="+"+String.valueOf(add-reduce);
					logger.info("get eScore="+eScore);
				}else if(reduce-add>0){
					eScore="-"+String.valueOf(reduce-add);
					logger.info("get eScore="+eScore);
				}
			}else{
				eScore="0";
			}
			add=0;
			reduce=0;
			logger.info("get eScore="+eScore+",classId="+clazz.getId()+
					",studentId="+student.getId()+",userId="+clazz.getUserId());
			comprehensiveQuality.setClassId(clazz.getId());
			comprehensiveQuality.setStudentId(student.getId());
			comprehensiveQuality.setVirtueScore(moralAchievement.getTotalScore());
			comprehensiveQuality.setWisdomScore(wScore);
			comprehensiveQuality.setExpandQualityScore(expandQuality.getTotalScore());
			comprehensiveQuality.setExtraScore(eScore);
			comprehensiveQuality.setUserId(clazz.getUserId());
			comprehensiveQuality.setIsDeleted(false);
			qualityService.saveComprehensiveQuality(comprehensiveQuality);
		}
	}
	@RequestMapping("createComprehensiveQuality")
	@SkipSecurityCheck
	@ResponseBody
	public Map createComprehensiveQuality(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		double total=0;
		int score=0;
		String className=request.getParameter("class_name");
		Classes cla =classesService.getClassByName(className);
		List<ComprehensiveQuality> comprehensiveQualities=qualityService.listComprehensiveQualityByClassId(cla.getId());
		int count=0;
		int count1=0;
		for(ComprehensiveQuality cq:comprehensiveQualities){
			if(cq.getIsDeleted()!=true){
				count++;
				int virtueScore=Integer.valueOf(cq.getVirtueScore());
				int wisdomScore=Integer.valueOf(cq.getWisdomScore());
				int expandQualityScore=Integer.valueOf(cq.getExpandQualityScore());
				String extraScore=cq.getExtraScore();
				logger.info("get virtueScore ="+ virtueScore +" ,wisdomScore=" +wisdomScore+
						",expandQualityScore"+expandQualityScore+",extraScore="+extraScore+",isDeleted="+cq.getIsDeleted());
				if("+".equals(extraScore.substring(0, 1))){
					score=Integer.valueOf(extraScore.substring(1).trim());
					logger.info("get score="+score);
					total=(double)((virtueScore*0.2)+(wisdomScore*0.6)+(expandQualityScore*0.2)+score);
				}else if("-".equals(extraScore.substring(0, 1))){
					score=Integer.valueOf(extraScore.substring(1).trim());
					logger.info("get score="+score);
					total=(double)((virtueScore*0.2)+(wisdomScore*0.6)+(expandQualityScore*0.2)-score);
				}else{
					total=(double)((virtueScore*0.2)+(wisdomScore*0.6)+(expandQualityScore*0.2));
				}
				logger.info("get total="+total);
				cq.setGrade(String.valueOf((int)total));
				int count2 =qualityService.updateComprehensiveQuality(cq);
				if(count2>0){
					count1++;
				}
			}
			
		}
		if(count==count1){
			map.put("success", "true");
		}else{
			map.put("success", "false");
		}
		return map;
	}
	@RequestMapping("deleteComprehensiveQuality")
	@SkipSecurityCheck
	@ResponseBody
	public Map deleteComprehensiveQuality(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		int  comprehensiveQualityId =Integer.valueOf(request.getParameter("id"));
		logger.info("get comprehensiveQualityId=" + comprehensiveQualityId);
		ComprehensiveQuality comprehensiveQuality =qualityService.getComprehensiveQualityById(comprehensiveQualityId);
		logger.info("get comprehensiveQuality:" +comprehensiveQuality);
		int count =qualityService.softDelete(comprehensiveQualityId);
		if(count>0){
			map.put("isDelete", "true");
		}else{
			map.put("isDelete", "false");
		}
		return map;

	}
}
